package com.wyz.note.project.demo;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @author: wei yz
 * @Date: 2024/1/28 13:41
 */
public class MergedCellInfoExtractor {
    public static void main(String[] args) throws IOException {
        // 打开Excel文件
        FileInputStream fis = new FileInputStream("D:\\test\\java\\test.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        XSSFSheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

        // 获取从第2行到第18行，第二列的合并单元格信息
        List<MergedCellInfo> mergedCellsInfo = getMergedCellsInfo(sheet, 34, 48, 1, 1); // 列索引需要减1，因为POI是基于0的索引

        // 输出结果
        System.out.println("合并单元格数量: " + mergedCellsInfo.size());
        for (MergedCellInfo info : mergedCellsInfo) {
            System.out.println("合并单元格起始行: " + (info.getFirstRow() + 1) + ", 合并行数: " + info.getMergedRows());
        }

        // 关闭工作簿和文件输入流
        workbook.close();
        fis.close();
    }

    public static List<MergedCellInfo> getMergedCellsInfo(XSSFSheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
        List<MergedCellInfo> mergedCellsInfo = new ArrayList<>();
        int numMergedRegions = sheet.getNumMergedRegions();

        for (int i = 0; i < numMergedRegions; i++) {
            CellRangeAddress mergedRegion = sheet.getMergedRegion(i);

            int mergedFirstRow = mergedRegion.getFirstRow();
            int mergedLastRow = mergedRegion.getLastRow();
            int mergedFirstCol = mergedRegion.getFirstColumn();
            int mergedLastCol = mergedRegion.getLastColumn();

            // 检查合并区域是否在指定的行列范围内
            if (mergedFirstRow >= firstRow && mergedLastRow <= lastRow && mergedFirstCol >= firstCol && mergedLastCol <= lastCol) {
                mergedCellsInfo.add(new MergedCellInfo(mergedFirstRow, mergedLastRow - mergedFirstRow + 1));
            }
        }

        return mergedCellsInfo;
    }

    // 辅助类，用于存储合并单元格的起始行和合并行数
    public static class MergedCellInfo {
        private int firstRow;
        private int mergedRows;

        public MergedCellInfo(int firstRow, int mergedRows) {
            this.firstRow = firstRow;
            this.mergedRows = mergedRows;
        }

        public int getFirstRow() {
            return firstRow;
        }

        public int getMergedRows() {
            return mergedRows;
        }
    }
}
